<template>
  <div style="height: 100%">
    <!-- :gutter="20" -->
    <el-row>
      <!-- v-model="content" -->
      <el-col :span="12">
        <quill-editor
          class="editor"
          v-model="content"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        ></quill-editor>
        <form action method="post" enctype="multipart/form-data" id="uploadFormMulti">
          <input
            style="display: none"
            :id="uniqueId"
            type="file"
            name="file"
            multiple
            accept="image/jpg, image/jpeg, image/png, image/gif"
            @change="uploadImg('uploadFormMulti')"
          />
        </form>
      </el-col>
      <el-col :span="12">
        <div class="editorBigHtml">
          <div class="editorhtmlTitle">预览效果</div>
          <!-- ql-editor /// editorboxHtml -->
          <div class="ql-editor editorboxHtml" v-html="content"></div>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      id="uploadtueditorBox"
      title="视频上传"
      width="30%"
      :close-on-click-modal="false"
      :visible.sync="videoUploadTag"
    >
      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-input v-model="videoLink" placeholder="请输入视频链接" clearable></el-input>
        </el-col>-->
        <el-col :span="12">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :limit="1"
              accept=".MP4, .MP4, .RMVB, .rmvb, .AVI, .avi, .MKV, .mkv"
              :show-file-list="false"
              :on-change="lalal"
              :on-remove="pihandleRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传视频文件，且不超过100MB</div>
            </el-upload>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="videoUploadTag = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- <iframe
      id="mainIframe"
      width="100%"
      height="100%"
      name="mainIframe"
      src="https://www.taobao.com/"
      frameborder="0"
      scrolling="auto"
    ></iframe>-->
  </div>
</template>
<script>
import { startLoading, endLoading } from '@/utils/loading.js'
import { upload } from '@/utils/allUrl.js'
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill'
import { ImageDrop } from 'quill-image-drop-module' // 拖动图片
import imageResize from 'quill-image-resize-module' // 缩放图片
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', imageResize)
// 富文本编辑器功能键
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: 'rtl' }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  //   [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ['clean'], // 清除文本格式-----['clean']
  ['image', 'video'] // 链接、图片、视频-----['link', 'image', 'video']
]
export default {
  data: function() {
    var self2 = this
    return {
      videoUploadTag: false, // 视频上传
      videoLink: '', // 视频链接
      uniqueId: 'uniqueId', // 图片上传
      //   富文本功能
      editorOption: {
        modules: {
          // 图片推拽上传
          imageDrop: false,
          //   图片缩放
          imageResize: {
            // 添加
            displayStyles: {
              // 添加
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar'] // 添加
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              video: function(value) {
                self2.videoUploadTag = true
              }
            }
          }
        },
        placeholder: '请在这里填写您想说的', // 提示
        theme: 'snow', // 主题 snow/bubble
        syntax: true // 语法检测
      },
      content: ''
    }
  },
  components: { quillEditor },
  mounted: function() {
    var _this = this
    var imgHandler = async function(image) {
      if (image) {
        var fileInput = document.getElementById(_this.uniqueId) // 隐藏的file文本ID
        fileInput.click() // 加一个触发事件
      }
    }
    _this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', imgHandler)
  },
  created: function() {},
  methods: {
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus(val) {}, // 获得焦点事件
    onEditorChange(val) {
      // 替换iframe为video
      const t = val.html.replace('<iframe', '<video style="width:200px; height:200px; outline:none; object-fit: fill;" controls').replace('</iframe>', '</video>')
      this.content = t
    }, // 内容改变事件
    // 上传图片
    async uploadImg() {
      var _this = this
      var quill = this.$refs.myQuillEditor.quill
      // 构造formData对象
      var formData = new FormData()
      formData.append('file', document.getElementById(_this.uniqueId).files[0])
      formData.append('type', 0)
      const { data: res } = await this.$http.post(`${upload}`, formData)
      if (res.code === '0000') {
        const Range = quill.getSelection()
        // 上传文件成功之后在富文本中回显(显示)
        quill.insertEmbed(Range !== null ? Range.index : 0, 'image', res.data[0])
        quill.setSelection(length + 1)
      } else {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true
        })
      }
    },
    // 添加视频
    async lalal(el) {
      let videoSize = el.size / (1024 * 1024) // 转成M格式
      videoSize = videoSize.toFixed(1) // 保留小数点后一位
      if (videoSize > 100) {
        const dele = this.$refs.upload.uploadFiles
        const index = dele.findIndex(item => item.uid === el.uid)
        dele.splice(index, 1)
        return this.$message({
          type: 'error',
          message: '图片超过最大限制100M',
          center: true
        })
      } else {
        startLoading(document.getElementById('uploadtueditorBox'))
        const file = el.raw
        const fd = new FormData()
        fd.append('file', file) // 传文件
        fd.append('type', 0) // 传文件
        const { data: res } = await this.$http.post(`${upload}`, fd)
        endLoading()
        if (res.code === '0000') {
          var quill = this.$refs.myQuillEditor.quill
          const Range = quill.getSelection()
          // 上传文件成功之后在富文本中回显(显示)
          quill.insertEmbed(Range !== null ? Range.index : 0, 'video', res.data[0])
          // quill.setSelection(length + 1)
          this.videoUploadTag = false // 关闭提示框
          this.$refs.upload.clearFiles() // 清空已上传文件
        } else {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true
          })
        }
      }
    },
    pihandleRemove() {}
    // 把实体格式字符串转义成HTML格式的字符串
    // escapeStringHTML(str) {
    //   str = str.replace(/&lt;/g, '<')
    //   str = str.replace(/&gt;/g, '>')
    //   return str
    // }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/editorcss.scss';
// .ql-editor {
//   line-height: normal !important;
//   //   overflow: hidden;
//   height: 500px;
// }
</style>
